package com.example.qnn_app;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import org.json.JSONObject;

import java.net.URI;
import java.util.UUID;
import java.nio.charset.StandardCharsets;

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "AutoCallAI";
    private static final int PERMISSION_REQUEST_CODE = 1001;

    private EditText inputDevice;
    private EditText inputHost;
    private EditText inputPort;
    private EditText inputUser;
    private EditText inputPass;
    private TextView statusView;
    private Button btnSaveConnect;
    private TelephonyManager telephonyManager;
    private PhoneStateListener phoneStateListener;
    private String deviceId;
    private String configuredDeviceCode;
    private Connection mqConnection;
    private Channel mqChannel;
    private String currentSessionId;
    private boolean isCallActive = false;

    // 权限列表
    private String[] permissions = {
            Manifest.permission.CALL_PHONE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化设备ID
        deviceId = generateDeviceId();

        // 初始化设置界面
        setupSettingsUi();

        // 检查权限
        checkPermissions();

        // 初始化电话管理器
        initTelephonyManager();

        // 如已保存配置，自动连接
        autoStartIfConfigured();
    }

    private void setupSettingsUi() {
        inputDevice = findViewById(R.id.input_device_code);
        btnSaveConnect = findViewById(R.id.btn_save_connect);

        SharedPreferences sp = getSharedPreferences("app_prefs", MODE_PRIVATE);
        inputDevice.setText(sp.getString("device_code", ""));

        btnSaveConnect.setOnClickListener(v -> {
            String dev = inputDevice.getText().toString().trim();
            if (dev.isEmpty()) {
                Toast.makeText(this, "请填写设备码", Toast.LENGTH_SHORT).show();
                return;
            }
            sp.edit().putString("device_code", dev).apply();

            // 保存后跳转到监控页
            Intent intent = new Intent(this, MonitorActivity.class);
            startActivity(intent);
            finish();
        });
    }

    private void autoStartIfConfigured() {
        SharedPreferences sp = getSharedPreferences("app_prefs", MODE_PRIVATE);
        String dev = sp.getString("device_code", null);
        boolean forceConfig = getIntent().getBooleanExtra("force_config", false);
        if (!forceConfig && dev != null && !dev.trim().isEmpty()) {
            Intent intent = new Intent(this, MonitorActivity.class);
            startActivity(intent);
            finish();
        }
    }

    private void updateStatus(String text) {
        if (statusView != null) statusView.setText("状态：" + text);
    }

    private void restartRabbitMqConsumer() {
        try { if (mqChannel != null && mqChannel.isOpen()) mqChannel.close(); } catch (Exception ignored) {}
        try { if (mqConnection != null && mqConnection.isOpen()) mqConnection.close(); } catch (Exception ignored) {}
        startRabbitMqConsumer();
    }

    private void startRabbitMqConsumer() {
        new Thread(() -> {
            try {
                // TODO：按你的 MQ 实际地址/账号修改
                String mqHost = "192.168.1.11";
                int mqPort = 5672;
                String mqUser = "admin";
                String mqPass = "111111";

                ConnectionFactory factory = new ConnectionFactory();
                factory.setHost(mqHost);
                factory.setPort(mqPort);
                factory.setUsername(mqUser);
                factory.setPassword(mqPass);
                factory.setAutomaticRecoveryEnabled(true);

                mqConnection = factory.newConnection();
                mqChannel = mqConnection.createChannel();

                String queueName = "call_task_" + configuredDeviceCode;
                // 声明队列（幂等），持久化
                mqChannel.queueDeclare(queueName, true, false, false, null);

                DeliverCallback callback = (consumerTag, delivery) -> {
                    try {
                        String body = new String(delivery.getBody(), StandardCharsets.UTF_8);
                        Log.d(TAG, "收到MQ消息: " + body);
                        // 期望格式示例：
                        // {"phone":"13812345678","device_id":"test_app_phone_device","time":"2025-10-10T01:42:02.555Z"}
                        JSONObject data = new JSONObject(body);
                        String sessionId = data.optString("session_id", "mq_" + UUID.randomUUID().toString().substring(0, 8));

                        // 设备码匹配校验（若消息包含 device_id 则必须匹配当前设备码）
                        String msgDeviceId = data.optString("device_id", "").trim();
                        if (!msgDeviceId.isEmpty() && configuredDeviceCode != null && !msgDeviceId.equals(configuredDeviceCode)) {
                            Log.w(TAG, "忽略MQ消息：device_id不匹配，期望=" + configuredDeviceCode + ", 实际=" + msgDeviceId);
                            return;
                        }

                        // 号码字段优先级：phone > phone_number > number
                        String phoneNumber = data.optString("phone",
                                data.optString("phone_number",
                                        data.optString("number", "")));
                        String timeStr = data.optString("time", "");
                        if (!timeStr.isEmpty()) {
                            Log.d(TAG, "任务时间: " + timeStr);
                        }
                        if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
                            Log.e(TAG, "MQ消息缺少号码");
                            return;
                        }
                        String finalPhone = phoneNumber.trim();
                        runOnUiThread(() -> makeCall(sessionId, finalPhone));
                    } catch (Exception e) {
                        Log.e(TAG, "处理MQ消息失败", e);
                    }
                };

                mqChannel.basicConsume(queueName, true, callback, consumerTag -> {});
                runOnUiThread(() -> {
                    Toast.makeText(this, "已开始监听队列: " + queueName, Toast.LENGTH_LONG).show();
                    updateStatus("已连接，监听 " + queueName);
                });

            } catch (Exception e) {
                Log.e(TAG, "连接RabbitMQ失败", e);
                runOnUiThread(() -> Toast.makeText(this, "RabbitMQ连接失败: " + e.getMessage(), Toast.LENGTH_LONG).show());
            }
        }).start();
    }
    // 移除旧的 WebView/JS Bridge 逻辑

    private void checkPermissions() {
        boolean allPermissionsGranted = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false;
                break;
            }
        }

        if (!allPermissionsGranted) {
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
        }
    }

    private void initTelephonyManager() {
        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

        phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String phoneNumber) {
                super.onCallStateChanged(state, phoneNumber);

                switch (state) {
                    case TelephonyManager.CALL_STATE_IDLE:
                        Log.d(TAG, "通话状态: 空闲");
                        if (isCallActive) {
                            sendCallStatusUpdate("ended");
                            isCallActive = false;
                        }
                        break;

                    case TelephonyManager.CALL_STATE_RINGING:
                        Log.d(TAG, "通话状态: 响铃中");
                        break;

                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        Log.d(TAG, "通话状态: 通话中");
                        if (!isCallActive) {
                            sendCallStatusUpdate("connected");
                            isCallActive = true;
                            // 开始AI对话
                            startAIConversation();
                        }
                        break;
                }
            }
        };

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                == PackageManager.PERMISSION_GRANTED) {
            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }





    private void makeCall(String sessionId, String phoneNumber) {
        currentSessionId = sessionId;
        sendCallStatusUpdate("dialing");

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                == PackageManager.PERMISSION_GRANTED) {
            try {
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:" + phoneNumber));
                startActivity(callIntent);
                Log.d(TAG, "开始拨号: " + phoneNumber);
                Toast.makeText(this, "正在拨号: " + phoneNumber, Toast.LENGTH_SHORT).show();
                return;
            } catch (Exception e) {
                Log.e(TAG, "ACTION_CALL 拨号失败，尝试降级 ACTION_DIAL", e);
            }
        }

        // 无权限或直拨失败时，降级到 ACTION_DIAL（弹出拨号器）
        try {
            Intent dialIntent = new Intent(Intent.ACTION_DIAL);
            dialIntent.setData(Uri.parse("tel:" + phoneNumber));
            startActivity(dialIntent);
            Toast.makeText(this, "无直拨权限，已打开拨号器: " + phoneNumber, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "ACTION_DIAL 也失败", e);
            sendCallStatusUpdate("failed");
            Toast.makeText(this, "无法拨号: " + phoneNumber, Toast.LENGTH_SHORT).show();
        }
    }

    private void endCall() {
        // 这里需要实现结束通话的逻辑
        // 由于Android限制，无法直接通过代码挂断电话
        // 可以提示用户手动挂断
        Toast.makeText(this, "请手动挂断电话", Toast.LENGTH_LONG).show();
        sendCallStatusUpdate("ended");
        isCallActive = false;
    }

    private void sendCallStatusUpdate(String status) {
        if (currentSessionId != null) {
            Log.d(TAG, "状态更新: session=" + currentSessionId + ", status=" + status);
        }
    }

    private void startAIConversation() {
        // 开始AI对话逻辑
        Log.d(TAG, "开始AI对话");

        // 这里可以启动语音识别和AI处理
        // 例如：开始录音，识别语音，发送给AI处理，播放回复
    }

    private void speakText(String text) {
        // 使用TTS播放文本
        // 这里需要集成Text-to-Speech功能
        Log.d(TAG, "播放AI回复: " + text);
    }

    private String generateDeviceId() {
        // 生成唯一的设备ID
        return "android_" + UUID.randomUUID().toString().substring(0, 8);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }

            if (allGranted) {
                Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                initTelephonyManager();
            } else {
                Toast.makeText(this, "需要所有权限才能正常工作", Toast.LENGTH_LONG).show();
            }
        }
    }


}
